<template>
  <div class="video-preview-app">
    <!-- Header -->
    <AppHeader 
      :current-user="currentUser"
      :show-search="false"
      @login="showLoginModal"
      @register="showRegisterModal"
      @logout="handleLogout"
    />

    <!-- Breadcrumb Navigation -->
    <nav class="breadcrumb-nav">
      <div class="breadcrumb-content">
        <div class="breadcrumb">
          <router-link to="/" class="breadcrumb-item">
            <i class="fas fa-home"></i>
            视频中心
          </router-link>
          <span class="breadcrumb-item" v-if="course">{{ course.name }}</span>
        </div>
      </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
      <!-- Loading State -->
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>正在加载课程信息...</p>
      </div>

      <!-- Error State -->
      <div v-else-if="error" class="error-state">
        <i class="fas fa-exclamation-triangle"></i>
        <h2>加载失败</h2>
        <p>{{ error }}</p>
        <button class="btn btn-primary" @click="loadCourse">
          <i class="fas fa-redo"></i>
          重新加载
        </button>
      </div>

      <!-- Course Content -->
      <div v-else-if="course" class="course-details">
        <!-- Course Header -->
        <div class="course-header">
          <div class="course-info">
            <h1 class="course-title">
              <i class="fas fa-video"></i>
              {{ course.name }}
            </h1>
            <p class="course-description">{{ course.description || '暂无描述' }}</p>
            <div class="course-meta">
              <div class="meta-item">
                <i class="fas fa-video"></i>
                <span>{{ course.chapters ? course.chapters.length : 0 }} 视频</span>
              </div>
              <div class="meta-item">
                <i class="fas fa-clock"></i>
                <span>创建于 {{ formatDate(course.createdAt) }}</span>
              </div>
              <div class="meta-item" v-if="course.lastModified">
                <i class="fas fa-edit"></i>
                <span>更新于 {{ formatDate(course.lastModified) }}</span>
              </div>
              <div class="meta-item" v-if="totalDuration">
                <i class="fas fa-hourglass-half"></i>
                <span>总时长 {{ formatDuration(totalDuration) }}</span>
              </div>
            </div>
          </div>
          <div class="course-actions">
            <router-link 
              :to="{ name: 'VideoCourse', query: { courseId: course.id } }" 
              class="btn btn-primary"
              v-if="currentUser && currentUser.id === course.userId"
            >
              <i class="fas fa-edit"></i>
              编辑课程
            </router-link>
            <button class="btn btn-outline" @click="shareCourse">
              <i class="fas fa-share"></i>
              分享
            </button>
          </div>
        </div>

        <!-- Course Progress -->
        <div class="progress-section" v-if="course.chapters && course.chapters.length > 0">
          <div class="progress-header">
            <h3>学习进度</h3>
            <span class="progress-text">{{ completedVideos }}/{{ course.chapters.length }} 完成</span>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
          </div>
        </div>

        <!-- Video List -->
        <div class="videos-section">
          <div class="section-header">
            <h3>视频列表</h3>
            <div class="view-controls">
              <button 
                class="view-btn"
                :class="{ active: viewMode === 'list' }"
                @click="viewMode = 'list'"
              >
                <i class="fas fa-list"></i>
              </button>
              <button 
                class="view-btn"
                :class="{ active: viewMode === 'grid' }"
                @click="viewMode = 'grid'"
              >
                <i class="fas fa-th-large"></i>
              </button>
            </div>
          </div>

          <div v-if="course.chapters && course.chapters.length > 0" 
               class="videos-container" 
               :class="{ 'grid-view': viewMode === 'grid' }">
            <div 
              v-for="(video, index) in course.chapters" 
              :key="video.id"
              class="video-item"
              @click="playVideo(video)"
            >
              <div class="video-thumbnail">
                <div class="thumbnail-placeholder">
                  <i class="fas fa-play-circle"></i>
                </div>
                <div class="video-duration" v-if="video.duration">
                  {{ formatDuration(video.duration) }}
                </div>
                <div class="video-number">{{ index + 1 }}</div>
              </div>
              <div class="video-content">
                <h4 class="video-title">{{ video.title || '未命名视频' }}</h4>
                <div class="video-description">{{ getContentPreview(video.description) }}</div>
                <div class="video-meta">
                  <span class="meta-item">
                    <i class="fas fa-clock"></i>
                    {{ formatDate(video.createdAt) }}
                  </span>
                  <span class="meta-item" v-if="video.lastModified">
                    <i class="fas fa-edit"></i>
                    更新于 {{ formatDate(video.lastModified) }}
                  </span>
                </div>
              </div>
              <div class="video-status">
                <i class="fas fa-check-circle" v-if="isVideoCompleted(video)"></i>
                <i class="far fa-circle" v-else></i>
              </div>
            </div>
          </div>

          <div v-else class="empty-videos">
            <i class="fas fa-video"></i>
            <h3>暂无视频</h3>
            <p>该课程还没有添加任何视频</p>
          </div>
        </div>

        <!-- Video Player Modal -->
        <div class="video-modal" v-if="currentVideo" @click="closeVideoModal">
          <div class="video-modal-content" @click.stop>
            <div class="video-modal-header">
              <h3>{{ currentVideo.title }}</h3>
              <button class="modal-close" @click="closeVideoModal">
                <i class="fas fa-times"></i>
              </button>
            </div>
            <div class="video-modal-body">
              <div class="video-player">
                <!-- 如果是上传的视频文件，使用原生video标签播放 -->
                <video 
                  v-if="isUploadedVideo(currentVideo.videoUrl)"
                  :src="getProxyVideoUrl(currentVideo.videoUrl)"
                  controls
                  class="video-player-element"
                  style="width: 100%; height: 100%; object-fit: cover;"
                >
                  您的浏览器不支持视频播放。
                </video>
                <!-- 如果是外部链接，使用iframe嵌入 -->
                <iframe 
                  v-else
                  :src="getEmbedUrl(currentVideo.videoUrl)"
                  frameborder="0"
                  allowfullscreen
                  class="video-iframe"
                ></iframe>
              </div>
              <div class="video-info" v-if="currentVideo.description">
                <h4>视频描述</h4>
                <p>{{ currentVideo.description }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Course Not Found -->
      <div v-else class="course-not-found">
        <i class="fas fa-exclamation-triangle"></i>
        <h2>视频课程不存在</h2>
        <p>您要查看的视频课程不存在或已被删除</p>
        <router-link to="/" class="btn btn-primary">
          <i class="fas fa-home"></i>
          返回首页
        </router-link>
      </div>
    </main>
  </div>
</template>

<script>
import AppHeader from '@/components/AppHeader.vue'
import apiService from '@/services/api.js'

export default {
  name: 'VideoPreviewPage',
  components: {
    AppHeader
  },
  data() {
    return {
      course: null,
      currentUser: null,
      currentVideo: null,
      viewMode: 'list',
      loading: false,
      error: null
    }
  },
  computed: {
    completedVideos() {
      if (!this.course || !this.course.chapters) return 0
      return this.course.chapters.filter(video => this.isVideoCompleted(video)).length
    },
    progressPercentage() {
      if (!this.course || !this.course.chapters || this.course.chapters.length === 0) return 0
      return Math.round((this.completedVideos / this.course.chapters.length) * 100)
    },
    totalDuration() {
      if (!this.course || !this.course.chapters) return 0
      return this.course.chapters.reduce((total, video) => total + (video.duration || 0), 0)
    }
  },
  mounted() {
    this.loadCourse()
    this.checkAuthStatus()
  },
  watch: {
  },
  methods: {
    async loadCourse() {
      const courseId = this.$route.query.courseId
      if (courseId) {
        this.loading = true
        this.error = null
        try {
          // 调用后端 API 获取视频课程详情
          const response = await apiService.getVideoCourse(courseId)
          if (response.success) {
            // 后端返回的数据结构是 {success, data: {videoCourse}}
            // 我们需要提取 videoCourse 并赋值给 course
            this.course = response.course || response.data
          } else {
            this.error = response.message || '获取课程信息失败'
          }
        } catch (error) {
          console.error('获取课程信息失败:', error)
          this.error = '获取课程信息失败: ' + (error.message || '未知错误')
        } finally {
          this.loading = false
        }
      }
    },
    checkAuthStatus() {
      const savedUser = localStorage.getItem('currentUser')
      if (savedUser) {
        this.currentUser = JSON.parse(savedUser)
      }
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      })
    },
    formatDuration(minutes) {
      if (!minutes) return '0:00'
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      return hours > 0 ? `${hours}:${mins.toString().padStart(2, '0')}` : `${mins}:00`
    },
    getContentPreview(content) {
      if (!content) return '暂无描述'
      return content.length > 80 ? content.substring(0, 80) + '...' : content
    },
    isVideoCompleted(video) {
      // 简单判断：如果有视频链接就认为完成
      return video.videoUrl && video.videoUrl.trim().length > 0
    },
    async playVideo(video) {
      if (video.videoUrl) {
        this.currentVideo = video
      } else {
        await this.$alert('该视频还没有设置视频链接', {
          title: '视频不可用',
          variant: 'warning'
        })
      }
    },
    closeVideoModal() {
      this.currentVideo = null
    },
    getEmbedUrl(url) {
      if (!url) return ''
      
      // YouTube
      if (url.includes('youtube.com/watch?v=')) {
        const videoId = url.split('v=')[1].split('&')[0]
        return `https://www.youtube.com/embed/${videoId}`
      }
      
      // YouTube short URL
      if (url.includes('youtu.be/')) {
        const videoId = url.split('youtu.be/')[1].split('?')[0]
        return `https://www.youtube.com/embed/${videoId}`
      }
      
      // Bilibili
      if (url.includes('bilibili.com')) {
        const bvMatch = url.match(/BV[\w\d]+/)
        if (bvMatch) {
          return `https://player.bilibili.com/player.html?bvid=${bvMatch[0]}`
        }
      }
      
      return url
    },
    
    // 判断是否为上传的视频文件
    isUploadedVideo(url) {
      // 上传的视频文件URL包含/uploads/videos/路径
      return url && url.includes('/uploads/videos/');
    },
    
    // 获取视频文件的代理URL
    getProxyVideoUrl(url) {
      // 如果是上传的视频文件，使用代理路径
      if (this.isUploadedVideo(url)) {
        // 将 http://localhost:3000/uploads/videos/... 转换为 /uploads/videos/...
        // 这样会通过前端代理访问
        const proxyPath = url.replace('http://localhost:3000', '');
        return proxyPath;
      }
      return url;
    },
    
    shareCourse() {
      const url = window.location.href
      if (navigator.share) {
        navigator.share({
          title: this.course.name,
          text: this.course.description,
          url: url
        })
      } else {
        // 复制到剪贴板
        navigator.clipboard.writeText(url).then(async () => {
          // 使用Toast提示而不是模态框
          this.$toast('课程链接已复制到剪贴板', {
            title: '复制成功',
            variant: 'success'
          })
        })
      }
    },
    showLoginModal() {
      // Handle login modal
    },
    showRegisterModal() {
      // Handle register modal  
    },
    handleLogout() {
      this.currentUser = null
      localStorage.removeItem('currentUser')
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css');

.video-preview-app {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8fafc;
}

/* Loading State */
.loading-state {
  text-align: center;
  padding: 3rem 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e2e8f0;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-state p {
  font-size: 12px;
  color: #64748b;
  margin: 0;
}

/* Error State */
.error-state {
  text-align: center;
  padding: 3rem 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.error-state i {
  font-size: 64px;
  color: #fbbf24;
  margin-bottom: 1rem;
}

.error-state h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.error-state p {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 2rem;
}

/* Button Styles */
.btn {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  border: 1px solid transparent;
}

.btn-primary {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.btn-primary:hover {
  background: #2563eb;
  border-color: #2563eb;
}

.btn-outline {
  background: transparent;
  border-color: #e2e8f0;
  color: #64748b;
}

.btn-outline:hover {
  border-color: #3b82f6;
  color: #3b82f6;
}

/* Breadcrumb Navigation */
.breadcrumb-nav {
  background: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 0.75rem 0;
}

.breadcrumb-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 2rem;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 12px;
  color: #64748b;
}

.breadcrumb-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  text-decoration: none;
  color: #64748b;
}

.breadcrumb-item:hover {
  color: #3b82f6;
}

/* Main Content */
.main-content {
  flex: 1;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  padding: 2rem;
}

.course-details {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

/* Course Header */
.course-header {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 2rem;
}

.course-info {
  flex: 1;
}

.course-title {
  font-size: 20px;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 0.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.course-title i {
  color: #ef4444;
}

.course-description {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 1rem;
  line-height: 1.6;
}

.course-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 11px;
  color: #64748b;
}

.meta-item i {
  color: #94a3b8;
}

.course-actions {
  display: flex;
  gap: 1rem;
}

/* Progress Section */
.progress-section {
  background: white;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.progress-header h3 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.progress-text {
  font-size: 11px;
  color: #64748b;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #e2e8f0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #ef4444, #f59e0b);
  transition: width 0.3s ease;
}

/* Videos Section */
.videos-section {
  background: white;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.section-header h3 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.view-controls {
  display: flex;
  gap: 0.5rem;
}

.view-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border: 1px solid #e2e8f0;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #64748b;
}

.view-btn:hover {
  border-color: #3b82f6;
  color: #3b82f6;
}

.view-btn.active {
  background: #3b82f6;
  border-color: #3b82f6;
  color: white;
}

/* Video List */
.videos-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.videos-container.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
}

.video-item {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.video-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.grid-view .video-item {
  flex-direction: column;
  gap: 0.75rem;
}

.video-thumbnail {
  position: relative;
  width: 120px;
  height: 68px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.grid-view .video-thumbnail {
  width: 100%;
  height: 160px;
}

.thumbnail-placeholder {
  color: white;
  font-size: 24px;
  opacity: 0.7;
}

.grid-view .thumbnail-placeholder {
  font-size: 48px;
}

.video-duration {
  position: absolute;
  bottom: 0.25rem;
  right: 0.25rem;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 0.125rem 0.375rem;
  border-radius: 3px;
  font-size: 9px;
  font-weight: 500;
}

.video-number {
  position: absolute;
  top: 0.25rem;
  left: 0.25rem;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 0.125rem 0.375rem;
  border-radius: 3px;
  font-size: 9px;
  font-weight: 500;
}

.video-content {
  flex: 1;
  min-width: 0;
}

.video-title {
  font-size: 13px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.video-description {
  font-size: 11px;
  color: #64748b;
  margin-bottom: 0.5rem;
  line-height: 1.4;
}

.video-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.video-status {
  display: flex;
  align-items: center;
  color: #10b981;
  font-size: 16px;
}

.video-status .far {
  color: #cbd5e1;
}

/* Empty State */
.empty-videos {
  text-align: center;
  padding: 3rem 2rem;
}

.empty-videos i {
  font-size: 48px;
  color: #cbd5e1;
  margin-bottom: 1rem;
}

.empty-videos h3 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.empty-videos p {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 1.5rem;
}

/* Video Modal */
.video-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 2rem;
}

.video-modal-content {
  background: white;
  border-radius: 12px;
  max-width: 900px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
}

.video-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #e2e8f0;
}

.video-modal-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.modal-close {
  background: #f1f5f9;
  border: none;
  border-radius: 6px;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #64748b;
  transition: all 0.2s ease;
}

.modal-close:hover {
  background: #e2e8f0;
  color: #1e293b;
}

.video-modal-body {
  padding: 1.5rem;
}

.video-player {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%;
  margin-bottom: 1.5rem;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.video-player-element {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-info h4 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.video-info p {
  font-size: 12px;
  color: #64748b;
  line-height: 1.6;
}

/* Error State */
.course-not-found {
  text-align: center;
  padding: 3rem 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.course-not-found i {
  font-size: 64px;
  color: #fbbf24;
  margin-bottom: 1rem;
}

.course-not-found h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.course-not-found p {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 2rem;
}

/* Responsive Design */
@media (max-width: 768px) {
  .main-content {
    padding: 1rem;
  }
  
  .course-header {
    flex-direction: column;
    gap: 1rem;
  }
  
  .course-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .section-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .view-controls {
    align-self: flex-end;
  }
  
  .videos-container.grid-view {
    grid-template-columns: 1fr;
  }
  
  .video-item {
    flex-direction: column;
  }
  
  .video-thumbnail {
    width: 100%;
    height: 160px;
  }
  
  .video-modal {
    padding: 1rem;
  }
}
</style>